package com.huixin.powermonitor.controller;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.aliyun.oss.ClientException;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huixin.powermonitor.DTO.LoginDTO;
import com.huixin.powermonitor.common.CodeUtil;
import com.huixin.powermonitor.common.QueryPageParam;
import com.huixin.powermonitor.common.Result;
import com.huixin.powermonitor.common.SmsTool;
import com.huixin.powermonitor.entity.Menu;
import com.huixin.powermonitor.entity.User;
import com.huixin.powermonitor.service.MenuService;
import com.huixin.powermonitor.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huixin
 * @since 2025-02-21
 */
@CrossOrigin(originPatterns = "*", maxAge = 3600)
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    public static User user1;
    String rcode;
    @GetMapping("/list")
    @ApiOperation("获取所有用户列表")
    public List<User> list() {
        return userService.list();
    }
    @GetMapping("/count")
    @ApiOperation("获取用户总数")
    public Integer count() {
        return userService.count();
    }

    @PostMapping("/save")
    @ApiOperation("新增用户")
    public Result save(@RequestBody User user) {
        List<User> list = userService.lambdaQuery().eq(User::getName, user.getName()).eq(User::getRole, user.getRole()).list();
        if (list.size() > 0) {
            return Result.fail("用户账号已存在");
        }
        list = userService.lambdaQuery().eq(User::getTelephone, user.getTelephone()).eq(User::getRole, user.getRole()).list();
        if (list.size() > 0) {
            return Result.fail("电话号码重复");
        }
        return userService.save(user) ? Result.suc("新增成功") : Result.fail("新增失败");
    }

    @PostMapping("/update")
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody User user) {
        List<User> list = userService.lambdaQuery().eq(User::getName, user.getName()).eq(User::getRole, 1).ne(User::getId, user.getId()).list();
        if (list.size() > 0) {
            return Result.fail("用户账号已存在");
        }
        list = userService.lambdaQuery().eq(User::getTelephone, user.getTelephone()).eq(User::getRole, 1).ne(User::getId, user.getId()).list();
        if (list.size() > 0) {
            return Result.fail("电话号码重复");
        }
        return userService.updateById(user) ? Result.suc("修改成功") : Result.fail("修改失败");
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除用户")
    public Result delete(@RequestBody User user) {
        return userService.removeById(user.getId()) ? Result.suc("删除成功") : Result.fail("删除失败");
    }

    @PostMapping("/modStatus/{id}")
    @ApiOperation("修改用户状态")
    public Result modStatus(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        if (user.getStatus() == 1)
            user.setStatus(0);
        else user.setStatus(1);

        return userService.updateById(user) ? Result.suc("状态修改成功") : Result.fail("状态修改失败");
    }

    @GetMapping("/info/{id}")
    @ApiOperation("获取用户信息")
    public Result info(@PathVariable("id") Long id) {
        User user = userService.getById(id);
//        user.setPassword("");
        return Result.suc(userService.getById(id));
    }

    @Transactional
    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除用户")
    public Result deleteBatch(@RequestBody Long[] id) {
        userService.removeByIds(Arrays.asList(id));
        return Result.suc("批量删除成功");
    }
//    @PostMapping("/listPage")
//    @ApiOperation("分页查询用户")
//    public Result listPage(@RequestBody QueryPageParam query) {
//
//        Page<User> page = new Page<>(query.getPageNum(), query.getPageSize());
//
//        IPage<User> result = userService.page(page);
//
//        return Result.suc(result.getTotal(), result.getRecords());
//    }
@PostMapping("/listPage")
@ApiOperation("分页查询用户")
public Result listPage(@RequestBody QueryPageParam query) {

    // 获取当前页码和每页数量
    int pageNum = query.getPageNum();
    int pageSize = query.getPageSize();

    // 创建分页对象
    Page<User> page = new Page<>(pageNum, pageSize);

    // 从 query 中获取查询参数
    HashMap<String, Object> params = query.getParam();

    // 构建查询条件
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

    // 用户名 name：模糊查询
    if (params.containsKey("name") && StringUtils.isNotBlank(params.get("name").toString())) {
        String name = params.get("name").toString();
        lambdaQueryWrapper.like(User::getName, name);
    }

    // 电话号码 telephone：模糊查询
    if (params.containsKey("telephone") && StringUtils.isNotBlank(params.get("telephone").toString())) {
        String telephone = params.get("telephone").toString();
        lambdaQueryWrapper.like(User::getTelephone, telephone);
    }

    // 性别 sex：精确匹配
    if (params.containsKey("sex") && StringUtils.isNotBlank(params.get("sex").toString())) {
        String sex = params.get("sex").toString();
        lambdaQueryWrapper.eq(User::getSex, sex);
    }

    // 用户状态 status：精确匹配
    if (params.containsKey("status")) {
        Object statusObj = params.get("status");
        if (statusObj != null && StringUtils.isNotBlank(statusObj.toString())) {
            Integer status = Integer.parseInt(statusObj.toString());
            lambdaQueryWrapper.eq(User::getStatus, status);
        }
    }

    // 执行分页查询
    IPage<User> result = userService.page(page, lambdaQueryWrapper);

    // 返回结果
    return Result.suc(result.getTotal(), result.getRecords());
}



//    @PostMapping("/listPage")
//    @ApiOperation("分页查询用户")
//    public Result listPage(@RequestBody QueryPageParam query) {
//        HashMap param = query.getParam();
//        String name = (String) param.get("name");
//        String telephone = (String) param.get("telephone");
//        String role = (String) param.get("role");
//        String sex = (String) param.get("sex");
//        String status = (String) param.get("status");
//        Page<User> page = new Page();
//        page.setCurrent(query.getPageNum());
//        page.setSize(query.getPageSize());
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
//            wrapper.like(User::getName, name);
//        }
//        if (StringUtils.isNotBlank(telephone) && !"null".equals(telephone)) {
//            wrapper.like(User::getTelephone, telephone);
//        }
//        if (StringUtils.isNotBlank(role) && !"null".equals(role)) {
//            wrapper.like(User::getRole, role);
//        }
//        if (StringUtils.isNotBlank(sex) && !"null".equals(sex)) {
//            wrapper.like(User::getSex, sex);
//        }
//        if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
//            wrapper.like(User::getStatus, status);
//        }
//        IPage result = userService.PageList(page, wrapper);
//        return Result.suc(result.getTotal(), result.getRecords());
//    }
    @PostMapping("/login_code")
    public Result login_code(@RequestBody LoginDTO params){
        String code=params.getCode();
        String telephone = params.getTelephone();
        System.out.println(code+"   "+telephone+"   "+ rcode );
        if(!code.equals(rcode)){
            return Result.fail("验证码错误，请重试！");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getTelephone,telephone);
        user1 = userService.getOne(queryWrapper);
        User user = userService.getOne(queryWrapper);
        StpUtil.login(user.getId());
        List<Menu> menuList = menuService.lambdaQuery().like(Menu::getMenuright, user.getRole()).list();
        HashMap res = new HashMap<>();
        res.put("user", user);
        res.put("menu", menuList);
        return Result.suc(res);
    }
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@RequestBody Map<String, String> params) {
        String name = params.get("name");
        String password = params.get("password");
        String mpassword = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,name);
        user1 = userService.getOne(queryWrapper);

        if (mpassword != null && !mpassword.isEmpty() && name != null && !name.isEmpty()) {
            List<User> list = userService.lambdaQuery().eq(User::getName, name).eq(User::getPassword, mpassword).list();
            if (!list.isEmpty()) {
                User user = list.get(0);
                if (user.getStatus() == null || user.getStatus() != 1) {
                    return Result.fail("用户已被注销");
                } else {
                    StpUtil.login(user.getId());
                    List<Menu> menuList = menuService.lambdaQuery().like(Menu::getMenuright, user.getRole()).list();
                    HashMap res = new HashMap<>();
                    res.put("user", user);
                    res.put("menu", menuList);
                    return Result.suc(res);
                }
            }
        }
        return Result.fail("用户名或密码错误，请重试！");
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody User user) {
        String mpassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(mpassword);
        List<User> list = userService.lambdaQuery().eq(User::getName, user.getName()).eq(User::getRole, 1).list();
        if (list.size() > 0){
            return Result.fail("用户已存在");
        }
        list = userService.lambdaQuery().eq(User::getTelephone, user.getTelephone()).eq(User::getRole, 1).list();
        if (list.size() > 0){
            return Result.fail("电话号码重复");
        }
        return userService.save(user) ? Result.suc("注册成功") : Result.fail("注册失败");
    }



    @GetMapping("/showuser")
    public  Result showuser(){
        return Result.suc(user1);
    }



    @GetMapping("/getAvatar/{name}")
    @ApiOperation("根据用户名或手机号获取头像")
    public Result getAvatar(@PathVariable("name") String name) {
        List<User> list = userService.lambdaQuery().eq(User::getName, name).list();
        if (list.size() > 0) {
            return Result.suc(list.get(0).getAvatar());
        }
        list = userService.lambdaQuery().eq(User::getTelephone, name).list();
        if (list.size() > 0) {
            return Result.suc(list.get(0).getAvatar());
        }
        return Result.fail("用户不存在");
    }

    @Transactional
    @GetMapping("/modAvatar")
    @ApiOperation("修改头像")
    public Result modAvatar(@RequestParam Integer id, String avatar) {
        User user = userService.getById(id);
        user.setAvatar(avatar);
        userService.updateById(user);
        return Result.suc(userService.getById(id));
    }

    @Transactional
    @GetMapping("/modName")
    @ApiOperation("修改用户名")
    public Result modName(@RequestParam Integer id, String name) {
        User user = userService.getById(id);
        if (name.isEmpty()) {
            return Result.fail("用户名不能为空");
        }
        if (user.getName().equals(name)) {
            return Result.fail("用户名不能修改为原名称");
        }
        List list = userService.lambdaQuery().eq(User::getName, name).ne(User::getId, id).list();
        if (list.size() > 0) {
            return Result.fail("用户名已存在,请换一个名称");
        } else {
            user.setName(name);
            userService.updateById(user);
            return Result.suc(userService.getById(id));
        }
    }

    @GetMapping("/modPwd")
    @ApiOperation("修改密码")
    public Result modPwd(@RequestParam Integer id, String password) {
        User user = userService.getById(id);
        String mpassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (password.isEmpty()) {
            return Result.fail("密码不能为空");
        }
        user.setPassword(mpassword);
        userService.updateById(user);
        return Result.suc(userService.getById(id));
    }

    @PostMapping("/repass/{id}")
    @ApiOperation("重置密码")
    public Result repass(@PathVariable Integer id) {
        User user = userService.getById(id);
        String mpassword = DigestUtils.md5DigestAsHex("123456".getBytes());
        user.setPassword(mpassword);
        return userService.updateById(user) ? Result.suc("重置成功") : Result.fail("重置失败");
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public SaResult logout() {
        if (StpUtil.isLogin()) {
            StpUtil.logout();
        }
        return SaResult.ok("退出成功");
    }
    @PostMapping("/sms")
    public Result smsXxs(@RequestBody User user, HttpServletRequest request) throws ClientException, com.aliyuncs.exceptions.ClientException {
        Map<String,Object> map = new HashMap<>();
        // 验证码（指定长度的随机数）
        String code = CodeUtil.generateVerifyCode(6);
//        cod=code;
        String TemplateParam = "{\"code\":\""+code+"\"}";
        // 短信模板id
        String TemplateCode = "SMS_471370438";
        SendSmsResponse response = SmsTool.sendSms(user.getTelephone(),TemplateParam,TemplateCode);
        map.put("verifyCode",code);
        map.put("phone",user.getTelephone());
        request.getSession().setAttribute("CodePhone",map);
        rcode=code;
        System.out.println("rcode = " + rcode);
        return Result.suc("验证码已成功发送。");
    }

}